import axios from 'axios';
import { message } from 'antd';

// 环境配置
const envConfig = {
  development: {
    baseURL: 'http://dev-api.example.com',
    proxy: '/api'
  },
  production: {
    baseURL: 'http://prod-api.example.com',
    proxy: ''
  }
};

// 创建axios实例
const service = axios.create({
  baseURL: envConfig[process.env.NODE_ENV || 'development'].baseURL,
  timeout: 5000
});

// 请求拦截器
let isRefreshing = false;
let requestsQueue: (() => void)[] = [];

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => response.data,
  async error => {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      if (!isRefreshing) {
        isRefreshing = true;
        try {
          const refreshToken = localStorage.getItem('refreshToken');
          const { data } = await axios.post('/api/refresh-token', { refreshToken });
          localStorage.setItem('token', data.token);
          requestsQueue.forEach(cb => cb());
          requestsQueue = [];
          originalRequest._retry = true;
          return service(originalRequest);
        } catch (refreshError) {
          console.log('刷新token失败', refreshError);
          message.error('登录状态已过期，请重新登录');
          localStorage.removeItem('token');
          localStorage.removeItem('refreshToken');
          window.location.href = '/login';
          return Promise.reject(refreshError);
        } finally {
          isRefreshing = false;
        }
      } else {
        return new Promise(resolve => {
          requestsQueue.push(() => {
            resolve(service(originalRequest));
          });
        });
      }
    }
    // 状态码友好提示
    const statusCodeMessages = {
      400: '请求错误，请检查参数',
      403: '拒绝访问，请联系管理员',
      404: '请求资源不存在',
      500: '服务器错误，请稍后重试'
    };
    const errorMessage = statusCodeMessages[error.response?.status] || '未知错误，请稍后重试';
    message.error(errorMessage);
    return Promise.reject(error);
  }
);

export default service;